from flask import Blueprint, request
from app.Service.AdminService  import AdminService
from app.Utils.response import success, error
from app.Utils.exceptions import BusinessException
from app.db  import db

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
service = AdminService(db)


@admin_bp.route('/login', methods=['POST'])
def login():
    """管理员登录"""
    data = request.get_json()

    # 校验必填参数
    phone = data.get('phone', '').strip()  # 去除前后空格
    password = data.get('password', '').strip()

    if not phone or not password:
        return error("缺少必要参数")

    try:
        user_info = service.login(phone, password)
        return success({
            "userInfo": user_info
        }, "登录成功")
    except BusinessException as e:
        # 修改此处，正确传递参数
        return error(message=e.message, code=e.code)
    except Exception as e:
        return error(f"服务器内部错误: {str(e)}", 500)

@admin_bp.route('/user/info/<int:id>', methods=['GET'])
def get_user(id):
    """获取用户信息"""
    try:
        result = service.get_user(id)
        return success(result, "用户信息获取成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")

@admin_bp.route('/user/update/<int:id>',methods=['POST'])
def update_user(id):
    """更新用户信息"""
    data = request.get_json()

    try:
        result = service.update_user(id, data)
        return success(result, "用户信息更新成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")

@admin_bp.route('/user/password/<int:id>', methods=['POST'])
def update_password(id):
    """更新用户密码"""
    data = request.get_json()

    try:
        result = service.update_password(id, data)
        return success(result, "用户密码更新成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")